package lucene.server.web.controller.admin;

 
import cn.hutool.db.Db;
import lombok.extern.slf4j.Slf4j;
import lucene.server.common.model.Result;
import lucene.server.common.utils.StringUtil;
import lucene.server.common.utils.SystemInfoUtil;
import lucene.server.core.LuceneService;
import lucene.server.core.model.IndexConfig;
import lucene.server.database.pool.PoolManager;
import lucene.server.web.LuceneServerInit;
import lucene.server.web.config.LuceneConfig;
import lucene.server.web.dao.SystemDao;
import lucene.server.web.model.AnalyseInfo;
import lucene.server.web.task.TaskPool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.sql.SQLException;
import java.util.*;


@RestController
@RequestMapping("/admin")
@Slf4j
public class AdminController {

    private static final AnalyseInfo analyseInfo =  new AnalyseInfo();

    @Autowired
    private LuceneServerInit luceneServerInit;

    @PostMapping(value = "/restartAll")
    public Result<?> restartAll() {
        luceneServerInit.restart();
        return Result.OK();
    }
    @PostMapping(value = "/restartIndex")
    public Result<?> restartIndex(@RequestBody IndexConfig indexConfig) {
        luceneServerInit.restartOne(indexConfig.getName());
        return Result.OK();
    }
    @PostMapping(value = "/forceMergeIndex")
    public Result<?> forceMergeIndex(@RequestBody IndexConfig indexConfig) {
        LuceneService.getIndex(indexConfig.getName()).forceMerge();
        return Result.OK();
    }
    @PostMapping(value = "/indexTable")
    public Result<?> indexTable(@RequestBody IndexConfig indexConfig, HttpServletRequest req) {
        TaskPool.runTask("sql_"+indexConfig.getName()+"重建任务");
        return Result.OK("重建任务提交成功");
    }

    /**
     *
     * */
    @GetMapping(value = "/getAnalyse")
    public Result<?> getAnalyse(HttpServletRequest req) throws SQLException {
        return  Result.OK(analyse());
    }
    /**
     *
     * */
    @GetMapping(value = "/systemGC")
    public Result<?> systemGC(HttpServletRequest req) {
        System.gc();
        return  Result.OK();
    }
    /**
     *
     * */
    @GetMapping(value = "/getParam")
    public Result<?> getParam(HttpServletRequest req) throws SQLException {
        return   Result.OK(Db.use().findAll("setting"));
    }

    /**
     * 日志获取
     * */
    @PostMapping(value = "/saveParam")
    public Result<?> saveParam(@RequestBody List<Map<String,String>> params) throws SQLException {
        SystemDao.updateSystemParam(params);
        return  Result.OK();
    }
    /**
     * 日志获取
     * */
    @GetMapping(value = "/getLog")
    public Result<?> getLog(@RequestParam(name = "page",required = true,defaultValue = "1")int page,HttpServletRequest req) throws SQLException {
        return  Result.OK(SystemDao.getJoblog(page));
    }
    private AnalyseInfo analyse()  {

        if (System.currentTimeMillis()-analyseInfo.getLastUpdate()<1000*5){
            return analyseInfo;
        }
        analyseInfo.newAnalyse();
        for (IndexConfig indexConfig : LuceneConfig.getIndexConfigs()){
            analyseInfo.getFiles().put(indexConfig.getName(),SystemInfoUtil.calculateFiles(indexConfig.getPath()+ File.separator+indexConfig.getName()));
            analyseInfo.setIndexDocNum(indexConfig.getName(),LuceneService.getIndex(indexConfig.getName()).getDocNums());
        }

        analyseInfo.setCpu( SystemInfoUtil.getCpuInfo());
        analyseInfo.setMemory(SystemInfoUtil.getMemoryInfo());
        analyseInfo.setIndex(LuceneConfig.getIndexConfigs());
        analyseInfo.getTasks().clear();
        TaskPool.taskCache.forEach((k,v)->{
            Map<String,Object> task = new HashMap<>();
            task.put("name", StringUtil.getTaskName( v.getName()));
            task.put("type",v.getClass().getSimpleName());
            task.put("plan",v.getTaskPlan());
            task.put("running",v.isRunning());
            analyseInfo.getTasks().add(task);
        });
        analyseInfo.getConns().clear();
        analyseInfo.setConns(PoolManager.getPoolInfo());
        analyseInfo.setLastUpdate(System.currentTimeMillis());
        return analyseInfo;
    }

}

